<?php

namespace app\admin\controller;

use app\common\Helper;
use app\admin\model\Advertise;
use app\admin\model\Ticket;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 收益
 */
class Profit extends Base
{

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 首页
     */
    public function getHomeFrame(){
        $startDay = date('Y-m-d') . ' -1 day';
        $endDay = date('Y-m-d 00:00:00');
        $startMonth = date("Y-m-01");
        $endMonth = date("Y-m-01 23:59:59")." +1 month -1 day";

        // 累计收益
        $totalWhere = [];
        // 广告收益
        $totalAd = $this->getAdProfit($totalWhere);
        // 优惠券收益
        $totalTicket = $this->getTicketProfit($totalWhere);
        $totalProfit = ($totalAd + $totalTicket);

        // 本月收益
        // 广告收益
        $monthAdWhere = [
            'payTime' => ['between time', [$startMonth, $endMonth]]
        ];
        $monthAd = $this->getAdProfit($monthAdWhere);
        // 优惠券收益
        $monthTicketWhere = [
            'a.createDate' => ['between time', [$startMonth, $endMonth]]
        ];
        $monthTicket = $this->getTicketProfit($monthTicketWhere);
        $monthProfit = ($monthAd + $monthTicket);

        // 昨日收益
        // 广告收益
        $dayAdWhere = [
            'payTime' => ['between time', [$startDay, $endDay]]
        ];
        $dayAd = $this->getAdProfit($dayAdWhere);
        // 优惠券收益
        $dayTicketWhere = [
            'a.createDate' => ['between time', [$startDay, $endDay]]
        ];
        $dayTicket = $this->getTicketProfit($dayTicketWhere);
        $dayProfit = ($dayAd + $dayTicket);

        $data = [
            'totalProfit' => $totalProfit ? : '0',
            'monthProfit' => $monthProfit ? : '0',
            'dayProfit' => $dayProfit ? : '0',
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 获取广告收益
     */
    public function getAdProfit($where){
        /*$adIds =  Advertise::where($where)->field('id')->select();
        $adIds = array_column($adIds, 'id');

        $advertiselocalconnectDB = db('advertiselocalconnect');
        $count = $advertiselocalconnectDB
            ->alias('a')
            ->join('advertiselocal b', 'b.id = a.advertiselocalId')
            ->where(['a.advertiseId' => ['in', $adIds]])
            ->field('b.advertiseForCharge')
            ->sum('b.advertiseForCharge');*/
        $storetradedetailDB = db('storetradedetail');
        //$count = $storetradedetailDB->sum('payMoney');
        $join = [
            ['advertise ad', 'ad.id = a.orderNO'],
            ['store b', 'b.id = a.payStoreId']
        ];
        $count = $storetradedetailDB->alias('a')->where($where)->join($join)->sum('a.payMoney');

        return $count;
    }

    /**
     * 获取优惠券收益
     */
    public function getTicketProfit($where){
        //$count = Userbuyticket::where($where)->sum('money');
        $platformearnDB = db('platformearn');
        //$count = $platformearnDB->where($where)->sum('earnings');
        $join = [
            ['ticket t', 't.id = a.ticketId'],
            ['store b', 'b.id = t.storeId'],
            ['user u', 'u.id = a.createOper'],
        ];
        $count = $platformearnDB->alias('a')->where($where)->join($join)->sum('a.earnings');

        return $count;
    }

    /**
     * 列表
     */
    public function getList(){
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $defaultWhere = $this->getDefaultWhere();
        $where = $defaultWhere;
        if (isset($param->storeName)) {
            $where['b.name'] = ['like', '%' . $param->storeName . '%'];
        }

        if($param->type == 1){
            // 广告收益
            $model = db('storetradedetail');
            $order = 'payTime DESC';
            $join = [
                ['advertise ad', 'ad.id = a.orderNO'],
                ['store b', 'b.id = a.payStoreId']
            ];
            $field = 'a.*, ad.advertiseTitle, ad.putAwayTime, ad.circleTime, b.name as storeName';
            $result = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->order($order)->select();
            $total = $model->alias('a')->where($where)->join($join)->count();
            $totalProfit = $model->alias('a')->where($where)->join($join)->sum('a.payMoney');
        }else{
            // 优惠券收益
            $model = db('platformearn');
            $order = 'createDate DESC';
            $join = [
                ['ticket t', 't.id = a.ticketId'],
                ['store b', 'b.id = t.storeId'],
                ['user u', 'u.id = a.createOper'],
            ];
            $field = 'a.*, t.name as ticketName, t.backgroundImg as ticketImg, t.buyTicketMoney, b.name as storeName, u.userName, u.imgUrl as userAvatar';
            $result = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->order($order)->select();
            $total = $model->alias('a')->where($where)->join($join)->count();
            $totalProfit = $model->alias('a')->where($where)->join($join)->sum('a.earnings');
        }

        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关收益');
        }
        /*$data = [
            'data' => $result,
            'totalProfit' => $totalProfit
        ];
        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data, $total);*/
        $data = [
            'status' => config('status.SUCCESS_STATUS'),
            'message' => self::MSG_SUCCESS,
            'data' => $result,
            'totalProfit' => $totalProfit ? : '0',
            'total' => $total
        ];
        return json($data);
    }

}